<template>
  <div v-loading.lock="loading" class="base-content system-department">
    <div class="basic-info">
      <el-form ref="queryForm" :inline="true" :model="queryForm">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="search" size="mini" placeholder="输入文件名称搜索" />
        </el-form-item>
      </el-form>
      <div class="base-content-operate">
        <el-button type="primary" icon="el-icon-plus" @click="onNew()">新增</el-button>
        <el-button type="primary" :icon="icon" size="mini" @click="onRowExpansion()">展开/收回</el-button>
      </div>
      <el-table ref="table" v-loading="tableLoad" :data="onSearch()"
        :tree-props="{ children: 'children', hasChildren: '!hasChildren' }" row-key="id" style="width: 100%"
        max-height="700px" fit highlight-current-row>
        <el-table-column prop="name" label="文件名称">
          <template slot-scope="{ row }">
            <div class="extend-content" :style="{ 'padding-left': `${row.level * 16}px` }" @click="onOpenExtend(row)">
              <template v-if="row.isFile">
                <span>
                  <!-- <BaseIconFont
                  class="open-extend-icon"
                  :class="{ 'expanded-row': row.expanded }"
                  icon="icon-xiajiantou"
                />-->
                  <i class="el-icon-document"></i>
                </span>
              </template>
              <i v-else class="el-icon-folder-opened"></i>
              <span v-if="row.name.indexOf(search) > -1">
                {{ row.name.substr(0, row.name.indexOf(search)) }}
                <span style="color: #f50">{{ search }}</span>
                {{ row.name.substr(row.name.indexOf(search) + search.length) }}
              </span>
              <span v-else>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="文件类型">
          <template slot-scope="{ row }">
            <span>{{ row.typeName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="childCount" label="文件数量">
          <template slot-scope="{ row }">
            <span v-if="row.childCount > 0">{{ row.childCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template slot-scope="{ row }">
            <div class="base-table-operation">
              <span v-if="!row.isFile">
                <el-link type="primary" @click="onView(row)">查看</el-link>
                <el-link type="primary" @click="onUpload(row)">上传</el-link>
                <el-link :disabled="row.isFile" type="primary" @click="onUpdate(row)">修改</el-link>
                <el-link type="danger" @click="onDelete(row)">删除</el-link>
              </span>
              <span v-else>
                <!-- <el-link type="primary" @click="PdfPreview(row)">预览</el-link> -->
                <el-link type="primary" @click="onDownload(row)">预览/下载</el-link>
                <el-link type="primary" @click="onChangeFolder(row)">移动</el-link>
                <el-link type="danger" @click="onDeleteFile(row)">删除</el-link>
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <DocumentFolder ref="DocumentFolder" :read-only="readonly" :edit-id="editId"
      :dialog-form-visible.sync="dialogFormVisible" />
    <DocumentFileUpload ref="DocumentFileUpload" v-model="isShowDialog" :read-only="readonly" :edit-id="editId"
      :dialog-upload-form-visible.sync="dialogUploadFormVisible" @success="dialogCallBack" />
    <DocumentFolderChange ref="DocumentFolderChange" v-model="isShowDialog" :read-only="readonly" :edit-id="editId"
      :dialog-change-folder-form-visible.sync="dialogChangeFolderFormVisible" @success="dialogCallBack" />
  </div>
</template>
<script>

const rebuildData = (value, arr) => {
  if (!arr) {
    return [];
  }
  const newarr = [];
  arr.forEach((element) => {
    if (element.name && element.name.toLowerCase().indexOf(value) > -1) {
      // const ab = rebuildData(value, element.children);
      const obj = {
        ...element,
        // children: ab,
      };
      newarr.push(obj);
    } else {
      if (element.childs && element.childs.length > 0) {
        const ab = rebuildData(value, element.childs);
        const obj = {
          ...element,
          childs: ab,
        };
        if (ab && ab.length > 0) {
          newarr.push(obj);
        }
      }
    }
  });
  return newarr;
};

import { deleteFolder } from "../../../api/Document/DocumentFolder.js";
import { deleteFile, getNodeList } from "../../../api/Document/DocumentFile.js";
import { formatData, getArrayIndex } from '@/utils/index'
import DocumentFolder from "./DocumentFolder.vue";
import DocumentFileUpload from "./DocumentFileUpload.vue";
import DocumentFolderChange from "./DocumentFolderChange.vue";
import { GetStaticFileInfo } from "@/api/Base"

export default {
  name: "DocumentFolderList",
  components: { DocumentFolder, DocumentFileUpload, DocumentFolderChange },
  data() {
    return {
      search: "",
      icon: "el-icon-arrow-down",
      editId: "",
      tableLoad: true,
      isexpandAll: false,
      loading: true,
      readonly: false,
      isShowDialog: false,
      expandRowkeys: [],
      list: [],
      count: 0,
      childCount: 0,
      queryForm: {
        name: "",
      },
      dialogFormVisible: false,
      dialogUploadFormVisible: false,
      dialogChangeFolderFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    onSearch() {
      const { search, tableData } = this;
      return rebuildData(search.toLowerCase(), tableData);
    },
    getList() {
      this.searchLoading = true;
      this.tableLoad = true;
      getNodeList(this.queryForm, this.pagination)
        .then((res) => {
          // 格式化数据
          const formatTableData = formatData(res.data, { level: 0 });
          // 默认展开
          this.isExpand(formatTableData, this.expandRowkeys);
          this.tableData = formatTableData;
        })
        .finally(() => {
          this.searchLoading = false;
          this.tableLoad = false;
          this.loading = false;
        });
    },
    // 是否展开
    isExpand(data, expandIds) {
      if (data.length) {
        data.forEach((v) => {
          v.expanded = expandIds.includes(v.id);
          // 只有父级展开 子级才会展开
          if (v.expanded && v.childs && v.childs.length) {
            this.isExpand(v.childs, expandIds);
          }
        });
      }
    },
    // 切换树形展开
    // 切换数据表格树形展开
    onRowExpansion() {
      if (this.isexpandAll) {
        this.isexpandAll = false;
        this.icon = "el-icon-arrow-down";
        this.toggleRowExpansion_forAll(this.tableData, false);
      } else {
        this.isexpandAll = true;
        this.icon = "el-icon-arrow-up";
        this.toggleRowExpansion_forAll(this.tableData, true);
      }
    },
    toggleRowExpansion_forAll(data, isExpansion) {
      data.forEach((item) => {
        this.$refs.table.toggleRowExpansion(item, isExpansion);
        console.log(item);
        if (
          item.childs !== undefined &&
          item.childs !== null &&
          item.childs !== 0
        ) {
          this.toggleRowExpansion_forAll(item.childs, isExpansion);
        }
      });
    },
    onNew() {
      var that = this;
      that.readonly = false;
      that.editId = "";
      that.$refs.DocumentFolder.formData = that.Helper.deepCopy(
        that.$refs.DocumentFolder.initData
      );
      that.dialogFormVisible = true;
    },
    onView(rowData) {
      this.readonly = true;
      this.editId = rowData.id;
      this.isShowDialog = true;
      this.$refs.DocumentFolder.formData = rowData;
      this.dialogFormVisible = true;
    },
    onDelete(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteFolder({ id: rowData.id })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    onDeleteFile(rowData) {
      this.Helper.deleteConfirm(() => {
        this.loading = true;
        deleteFile({ id: rowData.id })
          .then((res) => {
            this.getList();
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    onUpdate(rowData) {
      this.readonly = false;
      this.editId = rowData.id;
      this.isShowDialog = true;
      this.$refs.DocumentFolder.formData = rowData;
      this.dialogFormVisible = true;
    },
    onChangeFolder(rowData) {
      var that = this;
      that.readonly = false;
      that.editId = rowData.id;
      that.isShowDialog = true;
      that.$refs.DocumentFolderChange.formData.folderId = 0;
      that.dialogChangeFolderFormVisible = true;
    },
    // 上传文件
    onUpload(row) {
      this.readonly = false;
      this.editId = row.id;
      this.isShowDialog = true;
      this.dialogUploadFormVisible = true;
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList();
    },
    // 关闭弹框清空id
    closeDialog() {
      this.editId = "";
      this.readonly = false;
      this.getList();
    },
    // 查看子级
    onOpenExtend(row) {
      row.expanded = !row.expanded;
      // 展开
      if (row.expanded) {
        this.expandRowkeys.push(row.id);
      } else {
        // 收起
        this.expandRowkeys.splice(getArrayIndex(this.expandRowkeys, row.id), 1);
      }
      this.$refs.table.toggleRowExpansion(row, row.expanded);
    },
    onDownload(row) {
      console.log(row)
      GetStaticFileInfo(row.filePath, row.name)
      // const eleLink = document.createElement("a");
      // eleLink.download = row.ame;
      // eleLink.href = row.filePath;
      // eleLink.target = "_blank";
      // eleLink.click();
      // eleLink.remove();
    },
    // 弹框回调
    dialogCallBack() {
      this.getList();
    },
  },
};
</script>
<style lang="scss">
.system-department {
  .extend-content {
    cursor: pointer;

    .open-extend-icon {
      margin: 0 4px 0 0;
      transform: rotate(-90deg);
      transition: all 0.3s;
    }

    .expanded-row {
      transform: rotate(0);
    }
  }

  .el-table {
    height: unset;

    .el-table__expand-icon {
      display: none;
    }

    .el-table__indent,
    .el-table__placeholder {
      display: none;
    }
  }

  .el-table::before {
    position: relative;
  }
}

.avatar-uploader {
  margin-left: 5px;
}</style>
